package cn.gailvlun.gll.presentation.login;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.joda.time.DateTime;

import java.util.Calendar;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.databinding.ActivityCompleteProfileBinding;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.presentation.login.adapter.GenderType;
import cn.gailvlun.gll.presentation.login.viewmodel.CompleteProfileViewModel;
import cn.gailvlun.gll.util.DateUtil;
import cn.gailvlun.gll.util.ProfileUtil;
import cn.gailvlun.gll.util.ToastUtil;
import cn.gailvlun.gll.widget.NavigationBarView;
import cn.gailvlun.gll.widget.edittext.FilterType;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function5;


public class CompleteProfileActivity extends BaseActivity {

    public static void openActivity(Context context) {
        Intent intent = new Intent(context, CompleteProfileActivity.class);
        context.startActivity(intent);
    }

    private ActivityCompleteProfileBinding mBinding;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {

        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() != 0) {
                    // TODO: 18/01/2018 ghy 定位错误
                    ToastUtil.showShort("定位失败");
                    return;
                }
                mBinding.tvCity.setText(aMapLocation.getCity());
            }
        }
    };

    public AMapLocationClientOption mOption = new AMapLocationClientOption() {
        {
            setLocationMode(AMapLocationMode.Hight_Accuracy);
            setOnceLocation(true);
            setNeedAddress(true);
        }
    };

    @Override
    protected void initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_complete_profile);
        CompleteProfileViewModel viewModel = new CompleteProfileViewModel(mContext, mBinding);
        
        if (ProfileUtil.getProfile() != null && ProfileUtil.getProfile().getUid() != null) {
            viewModel.getNickname().set(ProfileUtil.getProfile().getName());

        }
        mBinding.setVm(viewModel);
        getCity();
    }

    private void getCity() {
        // 获取定位权限
        new RxPermissions(mContext)
                .request(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            //初始化定位
                            mLocationClient = new AMapLocationClient(getApplicationContext());
                            //设置定位回调监听
                            mLocationClient.setLocationListener(mLocationListener);
                            mLocationClient.setLocationOption(mOption);
                            mLocationClient.startLocation();
                            return;
                        }
                        // TODO: 18/01/2018 ghy 没有定位权限
                        ToastUtil.showShort("没有定位权限，无法获取地理位置");
                    }
                });
    }


    @Override
    protected void createHandler() {
        mBinding.nbv.setOnBackListener(new NavigationBarView.OnBackListener() {
            @Override
            public void onBack(NavigationBarView nb) {
                onBackPressed();
            }
        });
        mBinding.cetNick.startFilter(FilterType.NICKNAME);
        mBinding.cetInvite.startFilter(FilterType.INVITATION);

        Observable<CharSequence> obInvite = RxTextView.textChanges(mBinding.cetInvite);
        Observable<CharSequence> obName = RxTextView.textChanges(mBinding.cetNick);
        Observable<CharSequence> obGender = RxTextView.textChanges(mBinding.tvGender);
        Observable<CharSequence> obBirthday = RxTextView.textChanges(mBinding.tvBirthday);
        Observable<CharSequence> obCity = RxTextView.textChanges(mBinding.tvCity);

        Observable.combineLatest(
                obInvite,
                obName,
                obGender,
                obBirthday,
                obCity,
                new Function5<CharSequence, CharSequence, CharSequence, CharSequence, CharSequence, Boolean>() {
                    @Override
                    public Boolean apply(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3, CharSequence charSequence4, CharSequence charSequence5) throws Exception {
                        return judgeIfCompleteEnable(charSequence, charSequence2, charSequence3, charSequence4, charSequence5);
                    }
                })
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        mBinding.tvComplete.setEnabled(aBoolean);
                    }
                });
    }

    private boolean judgeIfCompleteEnable(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3, CharSequence charSequence4, CharSequence charSequence5) {
        boolean isInvite = charSequence.length() > 0;
        boolean isName = charSequence2.length() > 0;
        boolean isGender = charSequence3.length() > 0;
        boolean isBirthday = charSequence4.length() > 0;
        boolean isCity = charSequence5.length() > 0;

        return isInvite && isName && isGender && isBirthday && isCity;
    }

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {

        mBinding.setGenderType(GenderType.getGenderByBoolean(false));//默认女性
        mBinding.setBirthday(DateUtil.toCalendar(DateTime.now().toDate()));
    }

    @Override
    public void onBackPressed() {
        MaterialDialog.Builder builder = new MaterialDialog.Builder(mContext);
        builder.title(" 这是最后一步了,确定要退出吗 ？")
                .positiveText("再想想")
                .negativeText("退出")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                        ProfileUtil.logOut();
                        WelcomeActivity.openActivity(mContext, true);

                    }
                })
                .show();
    }

    public static class Util {
        public static String getBirthday(Calendar calendar) {
            if (calendar == null) {
                return null;
            }
            return DateUtil.format(DateUtil.DATE_PATTERN, calendar.getTime());
        }
    }
}
